package google

import (
	"encoding/json"
	"github.com/go-resty/resty/v2"
	"github.com/zeromicro/go-zero/core/logx"
	"navi-mumbai/common/xerr"
	"net/http"
	"time"
)

const TokenURI = "tokeninfo"

var logger = logx.WithDuration(time.Second)

type VerifyReq struct {
	GoogleToken  string `json:"googleToken"`
	ClientId     string `json:"clientId"`
	ClientSecret string `json:"clientSecret"`
}

type GoogleUserInfoData struct {
	Iss           string `json:"iss"`
	Azp           string `json:"azp"`
	Aud           string `json:"aud"`
	Sub           string `json:"sub"`
	Hd            string `json:"hd"`
	Email         string `json:"email"`
	EmailVerified string `json:"email_verified"`
	Nbf           string `json:"nbf"`
	Name          string `json:"name"`
	Picture       string `json:"picture"`
	GivenName     string `json:"given_name"`
	FamilyName    string `json:"family_name"`
	Locale        string `json:"locale"`
	Iat           string `json:"iat"`
	Exp           string `json:"exp"`
	Jti           string `json:"jti"`
	Alg           string `json:"alg"`
	Kid           string `json:"kid"`
	Typ           string `json:"typ"`
}

type VerifyResultResp struct {
	Code int                `json:"code"`
	Data GoogleUserInfoData `json:"data"`
}

// https://oauth2.googleapis.com/tokeninfo?id_token={idToken}
func (r *HttpClient) VerifyToken(req *VerifyReq) (resp *VerifyResultResp, err error) {
	resp = &VerifyResultResp{}
	var rsp *resty.Response

	rsp, err = r.cli.R().SetHeader("Accept", "application/json").SetQueryParams(map[string]string{
		"id_token": req.GoogleToken,
	}).Get(r.Host + TokenURI)

	logger.Infof("【Google】  rsp %s ", rsp.String())
	if err != nil {
		logger.Infof("【Google】 VerifyToken error %s ", err.Error())
		return
	}
	if rsp.IsError() {
		logger.Infof("【Google】 status %s error %s rsp %s ", rsp.Status(), rsp.String())
		err = xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, rsp.Status())
		return
	}

	err = json.Unmarshal(rsp.Body(), &resp.Data)
	if err != nil {
		logger.Infof("【Google】 Unmarshal data error %s ", err.Error())
		err = xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, err.Error())
		return
	}
	logger.Infof("【Google】  resp %s ", resp.Data)
	resp.Code = http.StatusOK
	return
}
